package com.homepage.fileter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * @author J
 */
//@Configuration
public class CustomGlobalFilterConfig {
    private final Logger log = LoggerFactory.getLogger(GlobalFilter.class);

    @Bean
    @Order(-1)
    public GlobalFilter a() {
        return (exchange, chain) -> {
            // first pre filter
            exchange.getRequest().mutate().headers(httpHeaders -> {
                httpHeaders.remove("Expect");
            }).build();

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // second post filter
            }));
        };
    }

    @Bean
    @Order(0)
    public GlobalFilter b() {
        return (exchange, chain) -> {
            // second pre filter
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getPath().pathWithinApplication().value();
            InetSocketAddress remoteAddress = request.getRemoteAddress();

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // first post filter"
                ServerHttpResponse response = exchange.getResponse();
                HttpStatus statusCode = response.getStatusCode();
                log.info("请求路径:{},远程IP地址:{},响应码:{}", path, remoteAddress, statusCode);
            }));
        };
    }
}
